﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using log4net;
using AutoFacUtils;
using Common;
using CashFlow.Db.Entity;
using CashFlow.Web.Common;
using CashFlow.Web.MyActionResult;
using CashFlow.Web.Def;
using CashFlow.Web.Filters;
using CashFlow.Web.Service;
using CashFlow.Web.Areas.ShopManage.Models.Order;
using CashFlow.Web.Areas.ShopManage.Models.Order.Result;
using IOrderService = CashFlow.Web.Areas.ShopManage.Service.IOrderService;
using CashFlow.Web.Validator;
using CashFlow.Web.Areas.ShopManage.Validator.Order;
using CashFlow.Web.Models;
using CashFlow.Db.DAL;
using System.Net.Configuration;
using System.ComponentModel;

namespace CashFlow.Web.Areas.ShopManage.Controllers
{
    [ShopManagerFilter]
    public class OrderController : Controller
    {
        private static ILog _logger = LogManager.GetLogger(typeof(OrderController));
        private IUserService GetUserService() { return AutoFacHelper.Get<IUserService>(); }
        private IOrderService GetOrderService() { return AutoFacHelper.Get<IOrderService>(); }
        private IShopUserService GetShopUserService() { return AutoFacHelper.Get<IShopUserService>(); }

        // GET: ShopManage/Order
        public ActionResult Index()
        {
            var userService = GetUserService();
            var ui = userService.GetLoginUser();
            var shopUserService = GetShopUserService();
            var ls = shopUserService.QueryShopAllUsers2(ui.Id, 1);
            var ls2 = ls.Select(x => Convert(x)).ToList();
            ViewBag.UserList = ls2;

            return View();
        }

        public ActionResult List()
        {
            return View();
        }

        [HttpPost]
        [ValidatorFilter(typeof(QueryOrderModelValidator))]
        public ActionResult QueryByWhere(QueryOrderModel model)
        {
            var userService = GetUserService();
            var ui = userService.GetLoginUser();
            var orderService = GetOrderService();
            var ls = orderService.QueryByWhere(
                        ui.Id
                        , model.Date
                        , model.OrderNo
                        , model.Buyer
                        , model.Seller
                        , model.State
                     );
            return MyCommonTool.CreateOperationResult(true, "", ls);
        }

        [HttpPost]
        [ValidatorFilter(typeof(UpdateOrderModelValidator))]
        public ActionResult UpdateOrder(UpdateOrderModel model)
        {
            var date = MyCommonTool.GetOrderDate();
            var service = GetOrderService();
            var result = service.UpdateOrder(
                            model.OrderId
                            , date
                            , model.BuyerUserId
                            , model.SellerUserId
                            , model.Amount
                         );
            return MyCommonTool.CreateOperationResult(
                        result == EUpdateOrderResult.Success
                        , EnumTool.GetDescription<EUpdateOrderResult, int>(result)
                        , null
                   );
        }

        public bool IsOrderIdValid(int orderId
            , int buyerUserId
            , int sellerUserId
            , int shopManageUserId)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var count = db.Queryable<OrderEntity>()
                              .InnerJoin<ShopUserEntity>((o, su) => o.BuyerUserId == su.UserId)
                              .Where((o, su) => su.ShopManagerUserId == shopManageUserId
                                    && o.Id == orderId)
                              .Select((o, su) => o.OrderNo)
                              .Count();
                return count > 0;
            }
        }

        [HttpPost]
        [ValidatorFilter(typeof(CreateOrderModelValidator))]
        public ActionResult CreateOrder(CreateOrderModel model)
        {
            var date = DateTime.Now.ToString("yyyy-MM-dd");
            var service = GetOrderService();
            var result = service.CreateOrder(model.BuyerUserId
                            , model.SellerUserId
                            , model.Amount
                            , date
                         );
            bool bSuccess = result == ECreateOrderResult.Success;
            string msg = EnumTool.GetDescription<ECreateOrderResult, int>(result);
            return MyCommonTool.CreateOperationResult(bSuccess, msg, "");
        }

        public ActionResult ReleaseOrder()
        {
            bool bSuccess = false;
            string msg = "";

            if (MyCommonTool.IsReleaseOrderTime())
            {
                var userService = GetUserService();
                var ui = userService.GetLoginUser();
                var orderService = GetOrderService();
                var date = MyCommonTool.GetOrderDate();
                bool b = orderService.IsExistOrder(ui.Id, date);
                if (b)
                {
                    bSuccess = orderService.ReleaseOrder(ui.Id, date);
                }
                else
                {
                    msg = "未查询到订单信息！";
                }
            }
            else
            {
                msg = "发布时间错误！";
            }

            ViewBag.Success = bSuccess;
            ViewBag.Msg = msg;

            return View();
        }

        [HttpPost]
        [ValidatorFilter(typeof(DateModelValidator))]
        public ActionResult QueryPremiumOrder(DateModel model)
        {
            var userService = GetUserService();
            var shop = userService.GetLoginShopInfo();
            var service = GetOrderService();
            var ls = service.QueryOrderByDate(shop.ShopManagerUserId, model.Date);
            return MyCommonTool.CreateOperationResult(true, "", ls);
        }

        public ActionResult PremiumOrder()
        {
            return View();
        }

        private OrderUserInfoModel Convert(UserInfoEntity entity)
        {
            return new OrderUserInfoModel
            {
                Name = entity.Name,
                Phone = entity.Phone,
                Id = entity.Id
            };
        }

        private OrderBuyerInfoModel Convert2(OrderAndUserInfo entity)
        {
            return new OrderBuyerInfoModel
            {
                UserId = entity.UserInfo.Id,
                Name = entity.UserInfo.Name,
                Amount = Math.Round(entity.OrderInfo.Amount * (1 + Consts.OrderIncreasePercent), 2)
            };
        }
    }
}